package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.product.api.domain.vo.CategoryVo;
import com.spzx.product.domain.Category;
import com.spzx.product.helper.CategoryHelper;
import com.spzx.product.mapper.CategoryMapper;
import com.spzx.product.service.CategoryService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 商品分类 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2024-10-26
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Override
    public List<Category> getCategoryTree(Long parentId) {
        //调用baseMapper中带条件查询的方法
        List<Category> categoryList = baseMapper.selectList(new LambdaQueryWrapper<Category>().eq(Category::getParentId, parentId));
        //对Category中的hasChildren属性赋值
        categoryList.forEach(category -> {
            //判断是否有父id的值是当前分类的id
            Long count = baseMapper.selectCount(new LambdaQueryWrapper<Category>().eq(Category::getParentId, category.getId()));
            if(count > 0){
                //证明有子分类
                category.setHasChildren(true);
            }else {
                category.setHasChildren(false);
            }
        });

        return categoryList;
    }

    @Override
    public String importCategory(List<Category> categoryList, boolean updateSupport, String operName) {
        //判决集合是否为空
        if (StringUtils.isNull(categoryList) || categoryList.size() == 0)
        {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (Category category : categoryList)
        {
            try
            {
                //数据库中是否已经存在该分类
//                Category category1 = baseMapper.selectOne(new LambdaQueryWrapper<Category>().eq(Category::getName,category.getName()));
                Category category1 = baseMapper.selectById(category.getId());
                if (StringUtils.isNull(category1))
                {
                    //设置添加人的名字
                    category.setCreateBy(operName);
                    //插入分类数据
                    baseMapper.insert(category);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、分类 " + category.getName() + " 导入成功");
                }
                else if (updateSupport)
                {
                    //设置更新者的名字
                    category.setUpdateBy(operName);
                    //更新
                    baseMapper.updateById(category);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、分类 " + category.getName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、分类 " + category.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、分类 " + category.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<CategoryVo> tree() {
        //调用自带的方法获取所有的分类信息
        List<Category> allCategoryList = baseMapper.selectList(null);
        //将所有的分类转换为CategoryVo类型
        List<CategoryVo> categoryVoList = allCategoryList.stream().map(item -> {
            CategoryVo categoryVo = new CategoryVo();
            //复制属性值
            BeanUtils.copyProperties(item, categoryVo);
            return categoryVo;
        }).collect(Collectors.toList());
        //将所有的分类信息转换为分类树
        return CategoryHelper.buildTree(categoryVoList);
    }

    @Override
    public List<CategoryVo> getOneCategory() {
        List<Category> allCategoryList = baseMapper.selectList(
                new LambdaQueryWrapper<Category>().eq(Category::getParentId, 0)
        );
        return allCategoryList.stream().map(item -> {
            CategoryVo categoryVo = new CategoryVo();
            BeanUtils.copyProperties(item, categoryVo);
            return categoryVo;
        }).collect(Collectors.toList());
    }

    //将CategoryVoList转换为分类树的方法
    private List<CategoryVo> getCategoryVoTree(List<CategoryVo> categoryVoList) {
        //创建一个返回的集合
        List<CategoryVo> categoryVoTree = new ArrayList<>();
        //遍历集合
        categoryVoList.forEach(categoryVo -> {
            //获取父id等于0的分类信息
            if(categoryVo.getParentId() == 0){
                //给当前分类信息添加子分类
                categoryVo = this.addAndFindChildren(categoryVo,categoryVoList);
                //将当前分类信息添加到树的集合中
                categoryVoTree.add(categoryVo);
            }
        });
        return categoryVoTree;
    }

    //给分类添加子分类的方法
    private CategoryVo addAndFindChildren(CategoryVo categoryVo, List<CategoryVo> categoryVoList) {
        //遍历集合
        categoryVoList.forEach(categoryVo1 -> {
            //判断categoryVo1的父id是否为categoryVo的id值
            if(categoryVo1.getParentId() == categoryVo.getId()){
                //证明categoryVo1是categoryVo的子分类
                categoryVo1 = addAndFindChildren(categoryVo1,categoryVoList);
                //将categoryVo1添加到categoryVo的孩子中
                categoryVo.getChildren().add(categoryVo1);
            }
        });
        return categoryVo;
    }
}
